package com.zhai.boot.interceptor;

import com.zhai.boot.annotation.CacheLock;
import com.zhai.boot.common.ServiceResult;
import com.zhai.boot.common.ServiceResultConstant;
import com.zhai.boot.util.JSONUtil;
import com.zhai.boot.util.MD5Util;
import com.zhai.boot.util.RedisUtil;
import com.zhai.boot.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.ResponseEntity;

/**
 * 防重复提交
 */
@Aspect
@Configuration
public class CacheLockInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    private static final String RESUBMIT = "resubmit";

    @Around("execution(public * *(..)) && @annotation(com.zhai.boot.annotation.CacheLock)")
    public Object interceptor(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        CacheLock lock = signature.getMethod().getAnnotation(CacheLock.class);
        String key = StringUtil.join(lock.prefix(), lock.delimiter(), MD5Util.md5Encrypt32Upper(JSONUtil.toStr(pjp.getArgs())));
        if (redisUtil.hasKey(key)) {
            redisUtil.expire(key, lock.expire(), lock.timeUnit());
            return ResponseEntity.ok().body(ServiceResult.failure(ServiceResultConstant.SYS_RESUBMIT));
        }
        redisUtil.set(key, RESUBMIT, lock.expire(), lock.timeUnit());
        return pjp.proceed();
    }
}
